import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Image, Button, Pagination, message, Divider } from "antd";
import type { PaginationProps } from "antd";
import { useState, useRef, useEffect } from "react";
import { useNavigate } from "react-router-dom";

import Open from "../../assets/imgs/open.svg";
import U13 from "../../assets/imgs/u13.svg";
import U26 from "../../assets/imgs/u26.png";
import Remove from "../Remove";
import SearchFiltering from "../SearchFiltering";
import { TaskItem, Search } from "./home";

import {
  useAnalysisTask,
  Task,
} from "~/components/Visualization/store/useTaskState";
import { delTaskDocument } from "~/hooks/Visualization/use-visualization-api";
import { useTasksList } from "~/hooks/home/use-home-api";
import { Mutation } from "~/modules/api-server/types";
import { MutationDeleteTaskArgs } from "~/modules/api-server/types2";
import { formatDate, formatDateTime } from "~/modules/shared/utils/common";
import { useWorkSpace } from "~/modules/workspace/store/use-workspace";
import { getContent } from "~/plugins/api-server";
import "./analysisList.scss";
import { RawWorkSpaceState, Scheduler } from "~/modules/worker/schedule";

interface Props {
  add: Function;
  edit: Function;
}

export const AnalysisList = (props: Props) => {
  // 获取task信息
  const { updateTask } = useAnalysisTask();
  const { workSpace, update } = useWorkSpace();
  const [params, setParams] = useState<Search>({
    name: "",
    page: 1,
    pageSize: 10,
    CreateDateRange: [],
    UpdateDateRange: [],
  });

  const { data, refetch }: any = useTasksList(params);
  const tasksList: TaskItem[] = data?.tasks.data;
  const total = data?.tasks.totalCount;

  const removeRef = useRef();
  // 搜索UI显示隐藏
  const [isFilter, setFilter] = useState(false);
  // 删除
  const [delObj, setDelObj] = useState<TaskItem>({
    id: "",
    name: "",
    created_at: "",
    updated_at: "",
    aircraftId: "",
    tailno: "",
    start_time: "",
    end_time: "",
  });

  const router = useNavigate();
  const [delTaskItem, { data: delData }] = useMutation<
    Mutation,
    MutationDeleteTaskArgs
  >(delTaskDocument, { client: getContent().explorer_apiServer });
  useEffect(() => {
    if (delData) {
      message.success("删除成功！");
      refetch();
    }
  }, [delData]);

  const onTaskItem = (value: TaskItem) => {
    const task: Task = {
      id: value.id,
      name: value.name,
      startTime: value.start_time,
      endTime: value.end_time,
      aircraftId: value.aircraftId,
      tailno: value.tailno,
      type: "edit",
      customParams: [],
      taskParams: [],
      flights: value.flights ?? [],
    };
    RawWorkSpaceState.startTime = value.start_time;
    RawWorkSpaceState.endTime = value.end_time;
    updateTask(task);
    workSpace.splitCharts = [];
    Scheduler.loading = false;
    update(workSpace);
    router("/visualization");
  };

  // 编辑
  const onEdit = (e: any, value: TaskItem) => {
    RawWorkSpaceState.startTime = value.start_time;
    RawWorkSpaceState.endTime = value.end_time;
    e.stopPropagation();
    props.edit(value);
  };
  // 删除
  const [delText, setDelText] = useState<string>("");
  const onDel = (e: any, value: TaskItem) => {
    e.stopPropagation();
    setDelObj(value);
    setDelText(`是否删除分析任务 ${value.name} ？`);
    removeRef.current && (removeRef.current as any).onDelete();
  };
  const onDelTask = () => {
    delTaskItem({
      variables: {
        input: {
          id: delObj.id,
        },
      },
    });
  };
  // 分页
  const onChange = (pageNumber: number, pageSize: number) => {
    const data = {
      name: "",
      page: pageNumber,
      pageSize,
      CreateDateRange: [],
      UpdateDateRange: [],
    };
    setParams(data);
  };
  // 页容量
  const onShowSizeChange: PaginationProps["onShowSizeChange"] = (
    current,
    pageSize
  ) => {
    const data = {
      name: "",
      page: current,
      pageSize,
      CreateDateRange: [],
      UpdateDateRange: [],
    };
    setParams(data);
  };
  // 新建分析
  const onAdd = () => {
    props.add();
  };
  // 过滤组件
  const onFilter = () => {
    const data = {
      name: "",
      page: 1,
      pageSize: 10,
      CreateDateRange: [],
      UpdateDateRange: [],
    };
    setParams(data);
    setFilter(!isFilter);
  };
  const onClose = (state: boolean) => {
    setFilter(state);
  };

  // 搜索
  const onSearch = async (text: string, createTime: any, updateTime: any) => {
    const data = {
      name: text,
      page: 1,
      pageSize: 10,
      CreateDateRange: createTime,
      UpdateDateRange: updateTime,
    };
    setParams(data);
  };

  // 分析任务列表
  const listItem = tasksList?.map((item: TaskItem, index: number) => (
    <div key={item.id} className="analysis-task-item">
      <div className="flex">
        <div className="w-40px">
          <Image width={30} preview={false} src={U13} />
        </div>
        <div>
          <p className="text-16px m-0">{item.name}</p>
          <div className="flex">
            <p className="text-12px color-#6C7280 m-0">
              机尾号： {item.tailno}
            </p>
            <p className="text-12px color-#6C7280 mb-0 ml-50px">
              时间段：{" "}
              {formatDate(item.start_time) + " ~ " + formatDate(item.end_time)}
            </p>
            <p className="text-12px color-#6C7280 mb-0 ml-50px">
              创建日期： {formatDateTime(item.created_at)}
            </p>
            <p className="text-12px color-#6C7280 mb-0 ml-50px">
              最后修改日期： {formatDateTime(item.updated_at)}
            </p>
          </div>
        </div>
      </div>
      <div className="flex">
        <Button
          className="color-#5E7CE0!"
          type="text"
          onClick={() => onTaskItem(item)}
        >
          <Image
            width={25}
            style={{ paddingRight: "5px" }}
            preview={false}
            src={Open}
          />
          打开
        </Button>
        <Button
          className="color-#5E7CE0!"
          type="text"
          icon={<EditOutlined />}
          onClick={(e) => onEdit(e, item)}
        >
          数据范围
        </Button>
        <Button
          className="color-#5E7CE0!"
          type="text"
          icon={<DeleteOutlined />}
          onClick={(e) => onDel(e, item)}
        >
          删除
        </Button>
      </div>
    </div>
  ));

  return (
    <div className="bg-#FFF">
      <div className="h-48px flex justify-between border-b border-#EAEEF7 pl-16px pt-4px pr-16px pb-4px">
        <div>
          QUIVER
          <Divider type="vertical" style={{ height: "24px" }} />
          <Button
            className="color-#5E7CE0!"
            type="text"
            size="large"
            icon={<PlusOutlined twoToneColor="#6C92FA" />}
            onClick={() => onAdd()}
          >
            新建分析
          </Button>
        </div>
        <div
          className="analysis-task-head-filter-btn"
          onClick={() => onFilter()}
        >
          <Image width={18} preview={false} src={U26} />
        </div>
      </div>
      {isFilter ? (
        <div className="bg-#e3e4f5 pl-10px pr-10px mt-3px mr-16px mb-3px ml-16px">
          <SearchFiltering close={onClose} filter={onSearch} />
        </div>
      ) : null}
      {/* {tabKey === "1" ? ( */}
      <div>
        <div
          className="overflow-auto"
          style={{ height: "calc(100vh - 190px)" }}
        >
          {listItem}
        </div>

        <div className="flex justify-end mt-16px mr-24px mb-16px ml-24px">
          <Pagination
            // showQuickJumper
            showSizeChanger
            current={params.page}
            total={total}
            onChange={onChange}
            onShowSizeChange={onShowSizeChange}
          />
        </div>
      </div>
      {/* </div> */}

      <Remove ref={removeRef} delText={delText} onDelTask={onDelTask} />
    </div>
  );
};
